<?php


namespace app\admin\controller;


use app\admin\Base\BaseController;
use think\Exception;
use think\facade\Request;
use think\facade\View;
use app\admin\model\ArticleCategory as ArticleCategoryModel;

class ArticleCategory extends BaseController
{
    //分类列表
    public function index(){
        if (Request::isAjax()) {
            $select = ArticleCategoryModel::select();
            return $this->jsonApi('','1',$select);
        }
        return View::fetch();
    }
    //类别删除
    public function del(){
        $article = ArticleCategoryModel::find(Request::post('id'));
        //判断是否是顶级标签
        if ($article['pid'] === 0){
            $article->where('pid',$article['id'])->delete();
        }
        $status = $article->delete();
        if ($status){
            $this->jsonApi('删除成功',1);
        }

        $this->jsonApi('删除失败',0);
    }

    //类别批量删除
    public function delAll(){
        $ids = Request::post('ids');
        if (empty($ids)){
            $this->jsonApi('未选数据',0);
        }
        $idsArr = explode(',',$ids);
        $status = ArticleCategoryModel::destroy($idsArr);
        if ($status){
            $this->jsonApi('批量删除数据成功',1);
        }
        $this->jsonApi('批量删除数据失败',0);
    }

    //类别添加
    public function add(){
        if (Request::isAjax()) {
            //获取登入参数
            $data = Request::param();
            //保存到数据库
            $articleCategory = new ArticleCategoryModel();
            $status = $articleCategory->save($data);
            if ($status){
                return $this->jsonApi('添加成功',1);
            }
            return $this->jsonApi('添加失败',0);
        }
        return View::fetch();
    }

    //类别编辑
    public function edit(){
        return View::fetch();
    }

    //是否启用
    public function status(){
        $data = Request::post();
        $article = ArticleCategoryModel::update(['status' => $data['status'], 'id' => $data['id']]);
        if (empty($article)){
            $this->jsonApi("设置失败",0);
        }
        $this->jsonApi("修改成功",1);
    }
    //返回树的json数据
    public function tree(){
        $select = ArticleCategoryModel::select();
        $items = [];
        foreach($select->toArray() as $value){
            $items[$value['id']] = $value;
        }
        $tree = [];
        foreach($items as $key => $value){
            if(isset($items[$value['pid']])){
                $items[$value['pid']]['children'][] = &$items[$key];
            }else{
                $tree[] = &$items[$key];
            }
        }
        return json($tree);
    }

}